<script setup lang="ts">
import { ref, reactive } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import useTestCalendarStore from '@/stores/modules/testCalendar';
import { mock_API } from '@/apis';
const { addGroup } = mock_API;
const testCalendarStore = useTestCalendarStore();
interface Form {
  name: string;
  color: string;
}
// 收集表单数据
const form = reactive<Form>({
  name: '',
  color: '#9e0142',
});
const formRef = ref<FormInstance>();
// 校验规则
const rules = reactive<FormRules<Form>>({
  name: [{ required: true, message: '请输入组名称', trigger: 'blur' }],
  color: [
    {
      required: true,
      message: '请选择颜色',
      trigger: 'change',
    },
  ],
});

// 预制的颜色数组
const predefineColors = ref([
  '#9e0142',
  '#d53e4f',
  '#f46d43',
  '#fdae61',
  '#fee08b',
  '#ffffbf',
  '#e6f598',
  '#abdda4',
  '#66c2a5',
  '#3288bd',
  '#5e4fa2',
]);
// 控制提交按钮的加载状态
const isLoading = ref(false);

// 提交按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  isLoading.value = true;
  const r = await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('submit!');
      // setTimeout(async () => {
      const res = await addGroup(form);
      console.log(res);
      isLoading.value = false;
      formEl.resetFields();
      testCalendarStore.drawerIsShow = false;
      // }, 3000);
    } else {
      isLoading.value = false;
      console.log('error submit!', fields);
    }
  });

  console.log(r);
};
// 重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<script lang="ts">
export default {
  name: 'GroupForm',
};
</script>

<template>
  <section>
    <el-form
      :model="form"
      :rules="rules"
      status-icon
      ref="formRef"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="组名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="选择颜色" prop="color">
        <el-color-picker v-model="form.color" show-alpha :predefine="predefineColors" />
      </el-form-item>
      <el-form-item>
        <div class="flex flex-1 items-center justify-between">
          <el-button type="primary" @click="submitForm(formRef)" :loading="isLoading">
            创建
          </el-button>
          <el-button @click="resetForm(formRef)">重置</el-button>
        </div>
      </el-form-item>
    </el-form>
  </section>
</template>

<style scoped>
/* PC电脑端 */
@media screen and (width <= 1024px) {
}
</style>
